import React, { useMemo, useState, useEffect } from 'react';
import { HandTm } from './hand';
import { build_it, load_plc_id, load_id } from '../cmd/load';
import { CurTip, for_obj, BtMenu, useHigh, obj_str, no_del, BtTxt, PanelFind, GridTable, filter_row, WaitUmd, is_empty, useCmd, loc } from 'sui';
import { urlWork } from 'nui';

const IterView = ({ reload, mod, setEvent }) => {
    const [main, setMain] = useState();
    const [plc, setPlc] = useState();
    const umd = useCmd(null, null);
    const [fin, setFin] = useState();
    const [high] = useHigh(140, 100);

    useEffect(() => {
        load_id(mod, v => setPlc(v));
        load_plc_id(mod, v => setMain(v));
        setFin(null);
    }, [mod]);

    const filterRow = useMemo(() => {
        if (is_empty(main)) {
            return null;
        }

        const lst = ["id", "name", "state", "trigger", "m"];

        return filter_row(main, lst, umd.filter);
    }, [main, umd.filter]);

    const buildMain = (v, tp="update") => {
        if (tp === "del") {
            const tmp = main.filter(d => d.uid !== v);
            tmp.forEach((d, i) => d["index"] = i + 1);

            return tmp;
        }

        const tmp = [];
        const set = {};

        v.forEach(d => {
            build_it(d);
            set[d.uid] = d;
        });

        if (!is_empty(main)) {
            main.forEach(d => {
                if (set[d.uid]) {
                    return;
                }

                tmp.push(d);
            });
        }

        for_obj(set, (k, v) => tmp.push(v));

        tmp.sort((a, b) => a.id > b.id);
        tmp.forEach((d, i) => d["index"] = i + 1);

        return tmp;
    };

    const reload_data = (v, tp="update") => {
        const ret = buildMain(v, tp);

        reload({
            v: ret,
            id: mod,
            type: "it",
        });

        setMain(ret);
    };

    const hret = (v, tp) => {
        if (!tp) {
            umd.hreturn(false);
            setFin(null);
            return;
        }

        reload_data(v);

        if (tp === "trigger") {
            setEvent("update");
        }

        umd.hreturn(false);
        setFin(null);
    };

    if (fin === "copy") {
        const tp = obj_str(umd.cur, "tp");

        if (tp === "timer") {
            return <HandTm umd={umd} hreturn={hret} data={main} cur_plc={plc}/>;
        }
    }

    if (fin === "edit") {
        const row = main.filter(d => d.id !== umd.cur.id);
        const tp = obj_str(umd.cur, "tp");

        if (tp === "timer") {
            return <HandTm umd={umd} hreturn={hret} data={row} cur_plc={plc}/>;
        }
    }

    if (fin === "new_timer") {
        return <HandTm umd={umd} hreturn={hret} data={main} cur_plc={plc}/>;
    }

    const hdel = (d) => {
        if (no_del()) {
            return;
        }

        umd.startWait();

        const uid = obj_str(d, "uid");

        urlWork(null, "config/del", {uid: uid, mod: "it"},
            r => {
                reload_data(uid, "del");
                umd.endWait();
            },
            e => umd.setWrong(loc("xgsb")));
    };

    const hAction = (d, v) => {
        umd.hcur(d, v);
        setFin(v);
    };

    const hcopy = (d) => {
        const tp = obj_str(d, "tp");
        if (tp === "trigger" || tp === "timer" || tp === "call") {
            hAction(d, "copy");
        }
    };

    const col = [
        {name: loc("xh"), key: 'index', width: 80, frozen: true},
        {name: loc("jkid"), key: 'id', width: 200, frozen: true},
        {name: loc("cz"), key: 'e_opt', width: 180, frozen: true, formatter: props => {
            const d = props.row;

            if (d.tp === "trigger" || d.tp === "timer" || d.tp === "call") {
                return (
                    <div className="inline-flex">
                        <BtTxt hcmd={() => hdel(d, umd)}>{loc("sc")}</BtTxt>
                        <BtTxt hcmd={() => hAction(d, "edit")}>{loc("sz")}</BtTxt>
                        <BtTxt hcmd={() => hcopy(d)}>{loc("cmd_134")}</BtTxt>
                    </div>
                );
            }
            else {
                return (
                    <div className="inline-flex">
                        <BtTxt hcmd={() => hdel(d, umd)}>{loc("sc")}</BtTxt>
                        <BtTxt hcmd={() => hAction(d, "edit")}>{loc("sz")}</BtTxt>
                    </div>
                );
            }
        }},
        {name: loc("lx"), key: 'ltp', width: 40},
        {name: loc("mg_158"), key: 'time', width: 100},
        {name: loc("jkms"), key: 'name', width: 200},
        {name: loc("jkqy"), key: 'state', width: 80},
        {name: loc("jkplc"), key: 'trigger', width: 130},
        {name: loc("jkmes"), key: 'm', width: 130},
    ];

    const Right = () => {
        const lst = [
            {key: "new_timer", val: loc("mg_273")},
        ];

        return (
            <div className="inline-flex">
                <BtMenu lst={lst} hcmd={v => hAction(null, v)}>
                    <div className="mt-1 text-blue-600">
                        {loc("cmd_135")}
                    </div>
                </BtMenu>
            </div>
        );
    };

    const Left = () => <CurTip label={obj_str(plc, "name")} cur={obj_str(plc, "ip")}/>;

    return (
        <div className="ml-8">
            <PanelFind left={<Left/>} right={<Right/>} cl="gray" hcmd={v => umd.setFilter(v)}/>
            <GridTable col={col} row={filterRow} high={high}/>
            <WaitUmd umd={umd}/>
        </div>
    );
};

export {IterView};
